#include "SOIL.h"
#include "colorData.h"
#include <stdlib.h>
#include <stdio.h>

int isColorInTab(colorData* buf,colorData col,int size)
{
  int i=0;
  for (i=0;i<size;i++)
    {
      if(isColorEqual(buf[i],col))
	return i;
    }
  /* absent from buffer */
  return -1;
}

char isColorEqual (colorData a,colorData b)
{

  return (a.r==b.r)
    &&
    (a.g==b.g)
    &&
    (a.b==b.b);
}

colorData* readColorFromImage (const char* pathToImage,int* size,unsigned char** img,int* w,int* h,int* c)
{
  int channels;
  int numberOfColor=0;
  int width,height;
  unsigned char* pt=SOIL_load_image(pathToImage,&width,&height,&channels,SOIL_LOAD_AUTO);
  printf("w %d h  %d \n",width,height);
  if (channels!=3)
    {
      printf("CARE IMAGE DOESNT HAVE 3 CHANNELS AS SUPPOSED\n");
    }
  *w=width;
  *h=height;
  *img=pt;
  *c=channels;
  colorData* tab = malloc(sizeof(*tab)*width*height);
  int i;
  for (i=0;i<width*height;i+=3)
    {
      colorData col;
      col.r=pt[i + 0];
      col.g=pt[i + 1];
      col.b=pt[i + 2];
      if(isColorInTab(tab,col,numberOfColor)==-1)
	{
	  tab[numberOfColor]=col;
	  numberOfColor++;
	}
    }
  *size=numberOfColor;
  return tab;
}
